package com.gdk.ksoft.ui.works;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gdk.ksoft.R;
import com.gdk.ksoft.assembly.dbhelper.FfindGoodsDbHelper;
import com.gdk.ksoft.data.entry.tables.ShoppingCartGoodsTable;
import com.gdk.ksoft.assembly.dialog.MessageBox;
import com.gdk.ksoft.assembly.dialog.NSingleProductDialog;
import com.gdk.ksoft.assembly.widget.ExtendedEditText;
import com.gdk.ksoft.assembly.utils.extensions.ControlUtils;
import com.gdk.ksoft.assembly.utils.extensions.FormatUtils;
import com.gdk.ksoft.assembly.utils.system.SQLiteUtils;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class TpdwActivity extends Activity {

    @ViewInject(R.id.ptpdw_txtJs)private TextView txtJs;//件数统计
    @ViewInject(R.id.ptpdw_txtSs)private TextView txtSs;//散数统计
    @ViewInject(R.id.ptpdw_llGoodsContainer)private LinearLayout llGoodsContainer;//商品表格容器
    @ViewInject(R.id.ptpdw_etDPrice)private ExtendedEditText etDPrice;//单价
    @ViewInject(R.id.ptpdw_etJPrice)private ExtendedEditText etJPrice;//件价

    private DbUtils dbUtils;//数据库操作对象
    private int kh_id,shdz_id;//客户ID，收货地址ID
    private int fz_id = 0;//分组ID
    private float jPrice = 0f;//商品件价
    private int hsgx = 1;//换算关系

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tpdw);
        ViewUtils.inject(this);
        dbUtils = SQLiteUtils.getInstance(this).getDbUtils();
        etJPrice.setOnFocusChangeListener(focusChangeListener);
        etDPrice.setOnFocusChangeListener(focusChangeListener);
        Intent intent = getIntent();
        if(intent!=null){
            kh_id = intent.getIntExtra("customerId",0);
            shdz_id = intent.getIntExtra("addressId",0);
            fz_id = intent.getIntExtra("tpdwId",0);
            findAllGoodsByTpdwId(this,dbUtils,fz_id);//根据同品多味分组ID查询所有商品
        }
    }

    /**
     * 页面视图点击事件
     * @param view
     */
    @OnClick(value={R.id.ptpdw_txtSubmitGoods})
    public void onViewClick(View view) {
        switch(view.getId()){
            case R.id.ptpdw_txtSubmitGoods://提交同品多味的商品数据
                if(llGoodsContainer.getChildCount()<=0){
                    Toast.makeText(this,"没有可操作的数据!",Toast.LENGTH_SHORT).show();
                    return;
                }
//                if(Float.compare(jPrice,0.00f) == 0){
//                    Toast.makeText(this,"请确定当前单价是否正确!",Toast.LENGTH_SHORT).show();
//                    return;
//                }
                saveGoodsListToDatabase(this,dbUtils);//保存数据值数据库
                break;
            default:
                break;
        }
    }

    /**
     * 编辑框焦点监听器
     */
    private View.OnFocusChangeListener focusChangeListener = new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(hasFocus){//如果获得焦点
                etDPrice.clearTextChangedListeners();
                etJPrice.clearTextChangedListeners();
                switch(v.getId()){
                    case R.id.ptpdw_etJPrice:
                        etJPrice.addTextChangedListener(jPriceWatcher);
                        break;
                    case R.id.ptpdw_etDPrice:
                        etDPrice.addTextChangedListener(dPriceWatcher);
                        break;
                }
            }
        }
    };

    /**
     * 件价编辑监听器
     */
    private TextWatcher jPriceWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            try {
                String jprice = ControlUtils.getNumberStringFromTextView(etJPrice);
                jPrice = Float.parseFloat(jprice);//获得全局的件价
                etDPrice.setText(FormatUtils.exactNumber(jPrice / hsgx, "0.00"));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    };

    /**
     * 单价编辑监听器
     */
    private TextWatcher dPriceWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {}
        @Override
        public void afterTextChanged(Editable s) {
            try {
                String dprice = ControlUtils.getNumberStringFromTextView(etDPrice);
                jPrice = Float.parseFloat(dprice) * hsgx;//重新取值件价
                etJPrice.setText(FormatUtils.exactNumber(jPrice, "0.00"));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    };

    /**
     * 根据同品多味分组ID查询所有商品
     * @param context
     * @param tpdwId
     */
    public void findAllGoodsByTpdwId(final Context context,final DbUtils dbUtils,final int tpdwId){
        new AsyncTask<Void,Void,Void>(){
            private List<ShoppingCartGoodsTable> goodsTableList = null;
            private String errorMessage = null;
            private ProgressDialog dialog = null;
            private HashMap<String,Object> priceInfo = null;//价格信息

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(context,"","正在加载...");
            }

            @Override
            protected Void doInBackground(Void... params) {
                try{
                    goodsTableList = FfindGoodsDbHelper.findAllGoodsByTpdwId(dbUtils, tpdwId,
                            kh_id, shdz_id);
                    if(goodsTableList!=null && goodsTableList.size()>=0){//获取商品网络维护价格
                        ShoppingCartGoodsTable shoppingCartGoodsTable = goodsTableList.get(0);
                        hsgx = shoppingCartGoodsTable.hsgx;//获取商品换算关系
                        priceInfo = NSingleProductDialog.requestGoodsPrice(kh_id,shdz_id,
                                shoppingCartGoodsTable.sp_id,hsgx);
                    }
                }catch (Exception e){
                    errorMessage = e.getMessage();
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog != null && dialog.isShowing()) dialog.dismiss();
                if(errorMessage!=null){
                    Toast.makeText(context, "查找商品出错!", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(goodsTableList == null || goodsTableList.size()<=0){
                    Toast.makeText(context,"没有该分组的商品!",Toast.LENGTH_SHORT).show();
                    return;
                }
                if(priceInfo!=null){//价格信息
                    float price = Float.parseFloat(priceInfo.get("scfcj").toString());//获取上次发出价
                    jPrice = (Float.compare(price,0.00f) == 0)?goodsTableList.get(0).bzxsdwj:price;//标准销售单位加
                }
                etJPrice.setText(FormatUtils.exactNumber(jPrice,"0.00"));
                etDPrice.setText(FormatUtils.exactNumber(jPrice/hsgx,"0.00"));
                initGoodsListContainer(goodsTableList);//初始化表格数据
            }
        }.execute();
    }

    /**
     * 初始化商品列表容器
     */
    public void initGoodsListContainer(List<ShoppingCartGoodsTable> goodsTableList){
        if(goodsTableList == null || goodsTableList.size() == 0){//列表数据为空，清理当前列表
            llGoodsContainer.removeAllViews();
            txtJs.setText("件数：0");
            txtSs.setText("散数：0");
            Toast.makeText(this,"当前没有商品数据!",Toast.LENGTH_SHORT).show();
            return;
        }

        for(final ShoppingCartGoodsTable item : goodsTableList){//购物车列表数据
            View view = View.inflate(this,R.layout.item_tbl_goodslst,null);
            TextView txtView = (TextView)view.findViewById(R.id.item_tbl_goodslst_txtName);
            txtView.setText(item.mc);//写入商品的名字到控件上
            final EditText etSs = (EditText) view.findViewById(R.id.item_tbl_goodslst_etSs);
            final EditText etJs = (EditText) view.findViewById(R.id.item_tbl_goodslst_etJs);
            etSs.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }
                @Override
                public void afterTextChanged(Editable s) {
                    try{
                        String ssStr = ControlUtils.getNumberStringFromTextView(etSs);
                        int intSs = Integer.parseInt(ssStr);
                        if(Math.abs(intSs) >= item.hsgx){
                            Toast.makeText(TpdwActivity.this,"数量超出商品规格,商品规格："
                                    + item.gg + item.hsdw,Toast.LENGTH_SHORT).show();
                        }
                        makeAcccount();//做数据统计
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            });
            etJs.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    try{
                        makeAcccount();//做数据统计
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            });
            view.setTag(item);//设置购物车商品对象
            llGoodsContainer.addView(view);//添加列表到视图对象中
        }
    }

    /**
     * 枚举的错误类型
     */
    public enum GoodsArgumentError{
        NUMBER_ERROR,//数量输入错误
        NAN_ERROR,//非法字符错误
        NONE_ERROR,//无错误
        NONE_DATA//无数据
    }

    /**
     * 做数据统计
     */
    public void makeAcccount(){
        int js = 0,ss = 0;//设置件数和散数
        for (int i = 0; i < llGoodsContainer.getChildCount(); i++) {
            View childView = llGoodsContainer.getChildAt(i);
            EditText etJs = (EditText) childView.findViewById(R.id.item_tbl_goodslst_etJs);
            EditText etSs = (EditText) childView.findViewById(R.id.item_tbl_goodslst_etSs);
            String JsStr = ControlUtils.getNumberStringFromTextView(etJs);
            String SsStr = ControlUtils.getNumberStringFromTextView(etSs);
            js += Integer.parseInt(JsStr);
            ss += Integer.parseInt(SsStr);
        }
        js += ss/hsgx;//计算正确的件数
        ss = ss%hsgx;//当前正确的散数
        txtJs.setText("件数："+js);
        txtSs.setText("散数："+ss);
    }

    /**
     * 检测列表中的数据值是否符合条件并计算能通过的数据
     * @return 数据错误类型
     */
    public GoodsArgumentError checkGoodsList(List<ShoppingCartGoodsTable> shoppingCartGoodsTableList){
        try {
            for (int i = 0; i < llGoodsContainer.getChildCount(); i++) {
                View childView = llGoodsContainer.getChildAt(i);
                EditText etJs = (EditText) childView.findViewById(R.id.item_tbl_goodslst_etJs);
                EditText etSs = (EditText) childView.findViewById(R.id.item_tbl_goodslst_etSs);
                String JsStr = ControlUtils.getNumberStringFromTextView(etJs);
                String SsStr = ControlUtils.getNumberStringFromTextView(etSs);
                int js = Integer.parseInt(JsStr);
                int ss = Integer.parseInt(SsStr);
                if ((js > 0 && ss < 0) || (js < 0 && ss > 0)) {
                    return GoodsArgumentError.NUMBER_ERROR;
                }
                if(!(js == 0 && ss == 0) && shoppingCartGoodsTableList!=null){//把能操作的数据添加到列表中去
                    ShoppingCartGoodsTable item = (ShoppingCartGoodsTable)childView.getTag();
                    if(ss>=item.hsgx){//当散数的输入数量超出了换算关系
                        ss = ss%item.hsgx;
                        js+=ss/item.hsgx;
                    }
                    item.bzlsj = jPrice/hsgx;//标准零售价
                    item.bzxsdwj = jPrice;//标准销售单位价
                    item.xsdwsl = js;
                    item.xsdwss = ss;
                    item.hsdwsl = ss + js*item.hsgx;
                    item.yfje = js*item.bzxsdwj + ss * item.bzxsdwj/item.hsgx;
                    shoppingCartGoodsTableList.add(item);
                }
            }
            if(shoppingCartGoodsTableList!=null && shoppingCartGoodsTableList.size() == 0){
                return GoodsArgumentError.NONE_DATA;
            }
        }catch (Exception e){
            e.printStackTrace();
            return GoodsArgumentError.NAN_ERROR;
        }
        return GoodsArgumentError.NONE_ERROR;
    }


    /**
     * 储存列表中的数据值到数据库中去
     */
    public void saveGoodsListToDatabase(final Context context,final DbUtils dbUtils){
        new AsyncTask<Void,Void,Void>(){
            private ProgressDialog dialog;
            private String errMessage;
            private GoodsArgumentError error;
            private List<ShoppingCartGoodsTable> shoppingCartGoodsTableList;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                shoppingCartGoodsTableList = new ArrayList<>();
                dialog = ProgressDialog.show(context,"","正在提交数据...");
            }

            @Override
            protected Void doInBackground(Void... params) {
                try{
                    error = checkGoodsList(shoppingCartGoodsTableList);//检测当前数据
                    if(error == GoodsArgumentError.NONE_ERROR){//如果没有错误,则保存当前的错误
                        dbUtils.saveAll(shoppingCartGoodsTableList);
                    }else{
                        if(error == GoodsArgumentError.NAN_ERROR){
                            errMessage = "输入的数量中包含非法字符!";
                        }else if(error == GoodsArgumentError.NUMBER_ERROR){
                            errMessage = "输入的数量不正确!";
                        }else{
                            errMessage = "当前无数据可操作!";
                        }
                    }
                }catch (Exception e){
                    errMessage = "提交数据失败!原因："+e.getMessage();
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                if(errMessage!=null){
                    Toast.makeText(context,errMessage,Toast.LENGTH_SHORT).show();
                }else{
                    ((Activity)context).finish();
                    Toast.makeText(context,"提交数据成功!",Toast.LENGTH_SHORT).show();
                }
            }
        }.execute();
    }

    /**
     * 检测是否需要有数据添加
     */
    public boolean isHasDataToAdd(){
        List<ShoppingCartGoodsTable> shoppingCartGoodsTableList = new ArrayList<ShoppingCartGoodsTable>();
        if(checkGoodsList(shoppingCartGoodsTableList) != GoodsArgumentError.NONE_DATA){
            final MessageBox msgBox = new MessageBox(this);
            msgBox.setMessage("当前有输入数据，确定放弃商品添加吗?");
            msgBox.onPositiveNegitiveClick(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    msgBox.dismiss();//关闭对话框
                    switch(v.getId()){
                        case MessageBox.ID_DIALOG_BUTTON_CANCEL:
                            break;
                        case MessageBox.ID_DIALOG_BUTTON_OK:
                            goBack();//退出该页面
                            break;
                    }
                }
            });
            msgBox.show();
            return true;
        }
        return false;
    }

    /**
     * 退出该页面
     */
    public void goBack() {
        this.finish();
        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    }

    @OnClick(value = {R.id.ptpdw_imgBack})
    public void OnBackClick(View view) {
        if(isHasDataToAdd()){
            return;//检测输入的数据
        }
        goBack();//退出该页面
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
            if(isHasDataToAdd()) {
                return true;//检测输入的数据
            }
            goBack();//退出该页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
